package com.webank.maling.ai.support;

import com.webank.maling.base.util.Json;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;

@Slf4j
public class AISupport {

    public static <T> T parseAIResponse(String response, Class<T> responseClass) {
        try {
            String jsonPart = extractJsonFromResponse(response);
            return Json.fromJson(jsonPart, responseClass);
        } catch (Exception e) {
            log.error("解析AI响应时发生错误: {}", response, e);
            return null;
        }
    }

    public static <T> T parseAIResponse(String response, Type type) {
        try {
            String jsonPart = extractJsonFromResponse(response);
            return Json.fromJson(jsonPart, type);
        } catch (Exception e) {
            log.error("解析AI响应时发生错误: {}", response, e);
            return null;
        }
    }

    /**
     * 从AI响应中提取JSON内容
     */
    private static String extractJsonFromResponse(String response) {
        // 查找JSON代码块
        String jsonBlockPattern = "```json\\s*\\n([\\s\\S]*?)\\n\\s*```";
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(jsonBlockPattern);
        java.util.regex.Matcher matcher = pattern.matcher(response);

        if (matcher.find()) {
            return matcher.group(1).trim();
        }

        // 查找直接的JSON对象
        int startIndex = response.indexOf('{');
        int endIndex = response.lastIndexOf('}');

        if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
            return response.substring(startIndex, endIndex + 1);
        }

        return null;
    }
}
